from lib.sensors import max98357
from utils import common
import lib.net.wifi as wifi
import sys

wifi.do_connect_wifi()
max98357.init()

text_list = ["清明时节雨纷纷，路上行人欲断魂。借问酒家何处有，牧童遥指杏花村。"]


def play(text):
    common.print_gc_info()
    json_data = wifi.UREQUEST_POST(
        "http://www.hanxiaoxin.cn:8080/tts",
        {
            "Text": text,
            "Codec": "wav",
            "EmotionCategory": "poetry",
            "VoiceType": 301000,
        },
    )
    audio_base64 = json_data["Audio"]
    audio_data = common.decode_base64(audio_base64)
    print(len(audio_data))
    common.print_gc_info()
    max98357.play_bytes(audio_data)


def play_with_buffer(text):
    common.print_gc_info()
    response = None
    try:
        response = wifi.UREQUEST_POST(
            "http://www.hanxiaoxin.cn:8080/tts",
            {
                "Text": text,
                "Codec": "wav",
                "EmotionCategory": "poetry",
                "VoiceType": 301000,
                "mime": "wav",
            },
            "raw",
        )

        while True:
            read_data = response.raw.read(1024 * 20)
            if not read_data:
                break

            # print(len(read_data))
            # common.print_gc_info()
            max98357.play_bytes(read_data)
    except Exception as e:
        sys.print_exception(e)
        response and response.close()


for t in text_list:
    play(t)
